package com.disease.chronic.Component;

import com.disease.chronic.Config.HttpSessionConfig;
import com.disease.chronic.Global.Result;
import com.disease.chronic.Service.DeepSeekService;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import lombok.Setter;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;

@Component
@ServerEndpoint(value = "/chat/ai/{id}",configurator = HttpSessionConfig.class)
public class AiWebSocket {

    static DeepSeekService deepSeekService;

    @Setter
    static ApplicationContext applicationContext;

    private static final ConcurrentHashMap<String,Session> sessionPoll = new ConcurrentHashMap<>();

    String username;

    @OnOpen
    public void onOpen(Session session, @PathParam("id") String id){
        username = id;
        sessionPoll.put(id,session);

        deepSeekService = applicationContext.getBean(DeepSeekService.class);

    }

    @OnMessage
    public void onMessage(String message,Session session) throws IOException {
        String call = (String) deepSeekService.call(message).getData();
        session.getBasicRemote().sendText(call);
    }

    public static void getIndicatorSuggest(String username,String suggest)  {

        try {
            sessionPoll.get(username).getBasicRemote().sendText(suggest);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }

    }

    @OnClose
    public void onClose(){
        sessionPoll.remove(username);
    }

}
